package com.sky.business.sys.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.event.AdJustDeviceInfoEvent;
import com.sky.business.sys.event.CmccCreateDeviceReportEvent;
import com.sky.business.sys.event.DeviceInfo;
import com.sky.business.sys.service.ReportMessageService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.config.CacheConstants;
import com.sky.common.utils.NumberUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.SimpleTimeZone;

/**
 * 上报服务实现类
 */
@Service
public class ReportMessageServiceImpl implements ReportMessageService {

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));


    @Override
    @Async("miniThreadPoolTaskExecutor")
    public void reportDeviceInfo(CameraConfig cameraConfig, SystemConfig systemConfig) throws Exception {
        DeviceInfo deviceInfo =DeviceInfo.valueOf(cameraConfig);
        CmccCreateDeviceReportEvent cmccCreateDeviceReportEvent = new CmccCreateDeviceReportEvent(systemConfig.getEdgeId(),cameraConfig.getCameraDeviceId(),200,"",deviceInfo);
        String msg = objectMapper.writeValueAsString(cmccCreateDeviceReportEvent);
        MQTTClientUtils.publish(MQTTClientUtils.CMCC_MQTT_CLIENT, systemConfig.getCmccReportingTopic(), CacheConstants.DEFAULT_QOS, msg);
    }

    @Override
    @Async("miniThreadPoolTaskExecutor")
    public void adjustDeviceInfo(CameraConfig cameraConfig, SystemConfig systemConfig) throws Exception {
        AdJustDeviceInfoEvent adJustDeviceInfoEvent = new AdJustDeviceInfoEvent(systemConfig.getEdgeId(), cameraConfig.getCameraDeviceId(), NumberUtil.toDecimal(cameraConfig.getCameraLongitude()),NumberUtil.toDecimal(cameraConfig.getCameraLatitude()) ,NumberUtil.toDecimal(cameraConfig.getCameraAltitude()),NumberUtil.toDecimal(cameraConfig.getPanAngle()) ,NumberUtil.toDecimal(cameraConfig.getTiltAngle()));
        AdJustDeviceInfoEvent.DeviceInfo deviceInfo = adJustDeviceInfoEvent.getMetadata().getDeviceInfo();
        if(deviceInfo.getLongitude()==null || deviceInfo.getLatitude()==null || deviceInfo.getAltitude()==null || deviceInfo.getPanAngleTrim()==null || deviceInfo.getTiltAngleTrim()==null){
            return;
        }
        String msg = objectMapper.writeValueAsString(adJustDeviceInfoEvent);
        MQTTClientUtils.publish(MQTTClientUtils.LOCAL_MQTT_CLIENT, cameraConfig.getDispatcherTopic(), CacheConstants.DEFAULT_QOS, msg);
    }
}
